<?php


namespace app\controller\admin;


use app\common\service\redis\PoolRedis;
use app\model\AdminStaff;
use app\model\AdminStaffIcCard;
use app\model\AdminSuperSim;
use app\model\AdminUser;
use app\util\ExcelHandle;
use app\util\ReturnCode;
use app\util\Tools;
use think\facade\Queue;
use think\facade\Request;
use think\facade\Validate;
use think\Response;

class SuperSim extends Base
{

    public function index(): Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $student_no = $this->request->get('student_no', '');
        $student_name = $this->request->get('student_name', '');
        $phone = $this->request->get('phone', '');
        $ic_card = $this->request->get('ic_card', '');
        $sim_card = $this->request->get('sim_card', '');
        $staff_type = $this->request->get('staff_type', '');
        // type 1--sim卡（一对一） 2--ic卡（一对多,仅职工）
        $type = $this->request->get('type/d', 1);

        $obj = (new AdminStaff())->alias('staff')
            ->join(['admin_school' => 'school'], 'school.id=staff.school_id');
        if ($student_no) {
            $obj->where('staff.student_no', 'like', '%' . $student_no . '%');
        }
        if ($student_name) {
            $obj->where('staff.name', 'like', '%' . $student_name . '%');
        }
        if ($phone) {
            $obj->where('staff.phone', 'like', '%' . $phone . '%');
        }
        if ($staff_type) {
            $obj->where('staff.type', $staff_type);
        }
        if ($school_id > 0) {
            $obj->where('staff.school_id', $school_id);
        }
        if ($type == 2) {
            $obj->join(['admin_staff_ic_card' => 'card'], 'staff.id=card.staff_id and card.is_delete = 0')
                ->where('card.ic_card', '<>', '');
            // IC卡查询
            if ($ic_card) {
                $obj->where('card.ic_card', $ic_card);
            }
        } else {
            $obj->join(['admin_staff_ic_card' => 'card'], 'staff.id=card.staff_id and card.is_delete = 0')
                ->where('card.sim_uid', '<>', '');
            // SIM卡查询
            if ($sim_card) {
                $obj->where('card.sim_uid', $sim_card);
            }
        }

        $listObj = $obj->where([
                'school.is_delete' => 0,
                'staff.is_delete' => 0
            ])
            ->group('staff.id')
            ->field("staff.id,staff.phone,staff.school_id,school.name school_name,staff.name staff_name,staff.student_no,staff.type,staff.sex,staff.smart_card,staff.sim_card")
            ->with(['icCard' => function($query) use ($type) {
                $query->where('is_delete', 0)->append(['dormitory.name']);
                if ($type == 2) {
                    $query->order('activate_time', 'desc');
                } else {
                    $query->order('sim_activate_time', 'desc');
                }
            }])
            ->append(['icCard.student','type_text'])
            ->paginate(['page' => $start, 'list_rows' => $limit])
            ->toArray();
        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total'],
            'typeList' => AdminStaff::TYPE_ARR
        ]);
    }

    public function userSearch(): Response {
        $school_id = Request::get('school_id/d');
        $keywords = $this->request->get('name', '');

        $obj = AdminStaff::alias('s')
            ->join(['admin_staff_ic_card' => 'c'], 's.id=c.staff_id')
            ->where('c.is_delete', 0)->where('s.is_delete', 0);
        $card_obj = AdminStaffIcCard::where('is_delete', 0)->where('sim_uid', '<>', '');
        if ($school_id > 0) {
            $obj->where('c.school_id', $school_id);
            $card_obj->where('school_id', $school_id);
        }
        if ($keywords) {
            $obj->where('s.name', 'like', "%{$keywords}%");
        }
        $card_staff = $card_obj->group('staff_id')->column('staff_id');
        $obj->where('c.staff_id','not in', $card_staff);

        $list = $obj->group('s.id')->field('s.id,s.name,s.school_id,s.phone,s.type,s.status')
            ->with('school')
            ->append(['status_text','type_text'])
            ->order('s.create_time', 'DESC')
            ->limit(20)->select()->toArray();
        return $this->buildSuccess([
            'list'  => $list
        ]);
    }

    public function add(): Response {
        // type 1--sim卡（一对一） 2--ic卡（一对多）
        $school_id = Request::post('school_id/d');
        $staff_id = Request::post('staff_id/d');
        $card = Request::post('card/s', '', 'strip_tags');
        $phone = Request::post('phone/s');
        $validate = Validate::rule([
            'school_id|学校'=>'require',
            'staff_id|学生'=>'require',
            'phone|手机号,' => 'require|mobile',
            'card|卡号' => 'require',
        ]);
        if (!$validate->check(input('post.'))) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }
        $where = [
            'staff_id' => $staff_id,
            'school_id' => $school_id,
            'is_delete' => 0
        ];
        $model = (new AdminStaffIcCard())->where($where)->select();
        if (!$model) {
            return $this->buildFailed(ReturnCode::ADD_FAILED, '未授权宿舍');
        }
        $staff = AdminStaff::find($staff_id);
        $staff->sim_card = $card;
        $staff->phone = $phone;

        AdminStaffIcCard::update(['sim_uid' => $card], $where);

        if ($staff->save()) {
            $redis = PoolRedis::instance();
            $redis->hSetNx("smartCards", $card, $staff->id);
            return $this->buildSuccess();
        }
        return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
    }

    public function edit(): Response
    {
        $staff_id = Request::post('staff_id/d');
        $card = Request::post('card/s', '', 'strip_tags');
        $validate = Validate::rule([
            'staff_id|学生'=>'require',
            'card|卡号' => 'require',
        ]);
        if (!$validate->check(input('post.'))) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }
        $staff = AdminStaff::where([
            'id' => $staff_id,
            'is_delete' => 0
        ])->find();
        if (!$staff) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND);
        }
        // 修改卡号后重置激活时间
        $old_card = $staff->sim_card;
        $staff->sim_card = $card;
        if ($old_card && $old_card != $card) {
            $update['sim_uid'] = $card;
            $update['sim_activate_time'] = 0;
            AdminStaffIcCard::update($update, [
                'staff_id' => $staff_id,
                'school_id' => $staff->school_id,
                'is_delete' => 0
            ]);
        }
        if ($staff->save()) {
            $redis = PoolRedis::instance();
            if ($old_card && $old_card != $card) {
                // 删除卡号
                $redis->hDel("smartCards", $old_card);
            }
            $redis->hSetNx("smartCards", $card, $staff->id);
            return $this->buildSuccess();
        }
        return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
    }

    public function del(): Response {
        $flag = $this->request->get('flag', '');
        $ids = $this->request->get('id', '');

        $redis = PoolRedis::instance();
        // 批量删除,id为staff的id
        if ($flag == 'all') {
            $idList = explode(',', $ids);
            foreach ($idList as $id) {
                AdminStaffIcCard::update(
                    ['sim_activate_time' => 0, 'sim_uid' => ''],
                    ['is_delete' => 0, 'staff_id' => $id]
                );
                AdminStaff::update(['sim_card' => ''], [
                    'id' => $id
                ]);
            }
        } else {
            $model = (new AdminStaffIcCard())->where('id', $ids)
                ->where('is_delete', 0)->find();
            if (!$model) {
                return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND);
            }
            $model->sim_uid = '';
            $model->sim_activate_time = 0;
            $model->save();
            // 单个删除学生SIM卡记录, 如果最后一条记录也被删除，则删掉学生SIM卡
            $exists = (new AdminStaffIcCard())->where('staff_id', $model->staff_id)
                ->where('is_delete', 0)->findOrEmpty();
            if ($exists->isEmpty()) {
                $model->staff->sim_card = '';
                $model->staff->save();
                $redis->hDel("smartCards", $model->staff->sim_card);
            }
        }
        return $this->buildSuccess();
    }

    public function download(): Response {
        // type 1--sim卡（一对一） 2--ic卡（一对多,仅职工）
        $type = Request::get('type/d', 1);
        $title = $type == 2 ? 'IC卡' : '超级SIM卡';
        $titles = [['id' => '序号'],['school_name' => '学校名称'], ['student_no'=>'学号'],['staff_name'=>'姓名'],['sex' => '性别'],['type_text'=> '身份'],['phone'=>'手机号码'],['dormitory_name'=>'宿舍楼'],['student_dormitory_name'=>'宿舍间'],['card'=>$title],['activate_time'=>'激活时间']];

        $school_id = $this->request->get('school_id', 0);
        $student_no = $this->request->get('student_no', '');
        $student_name = $this->request->get('student_name', '');
        $phone = $this->request->get('phone', '');
        $staff_type = $this->request->get('staff_type', '');

        $obj = (new AdminStaff())->alias('staff')
            ->join(['admin_school' => 'school'], 'school.id=staff.school_id')
            ->where([
                'school.is_delete' => 0,
                'staff.is_delete' => 0
            ]);

        if ($student_no) {
            $obj->where('staff.student_no', 'like', '%' . $student_no . '%');
        }
        if ($student_name) {
            $obj->where('staff.name', 'like', '%' . $student_name . '%');
        }
        if ($phone) {
            $obj->where('staff.phone', 'like', '%' . $phone . '%');
        }
        if ($staff_type) {
            $obj->where('staff.type', $staff_type);
        }
        if ($school_id > 0) {
            $obj->where('staff.school_id', $school_id);
        }
        if ($type == 2) {
            $obj->join(['admin_staff_ic_card' => 'card'], 'staff.id=card.staff_id and card.is_delete = 0')
                ->where('card.ic_card', '<>', '');
        } else {
            $obj->where('staff.sim_card', '<>', '');
        }

        $listObj = $obj->group('staff.id')
            ->field("staff.id,staff.phone,staff.school_id,school.name school_name,staff.name staff_name,staff.student_no,staff.type,staff.sex,staff.sim_card")
            ->with(['icCard' => function($query) use ($type) {
                $query->where('is_delete', 0)->append(['dormitory.name']);
                if ($type == 2) {
                    $query->order('activate_time', 'desc');
                } else {
                    $query->order('sim_activate_time', 'desc');
                }
            }])
            ->append(['icCard.student','type_text'])
            ->select()->toArray();

        $exportData = [];
        $len = 1;
        foreach ($listObj as $datum) {
            $datum['staff_name'] .= "\t";
            $datum['student_no'] .= "\t";
            $datum['phone'] .= "\t";
            foreach ($datum['icCard'] as $key => $icCard) {
                $datum['id'] = $len;
                $datum['dormitory_name'] = $icCard['dormitory_name'];
                $datum['student_dormitory_name'] = $icCard['student_dormitory_name'];
                if ($type == 2) {
                    $datum['activate_time'] = $icCard['activate_time']."\t";
                    $datum['card'] = $icCard['ic_card']."\t";
                } else {
                    $datum['card'] = $datum['sim_card']."\t";
                    $datum['activate_time'] = $icCard['sim_activate_time']."\t";
                }
                array_push($exportData, $datum);
                $len++;
            }
        }
        ExcelHandle::downLoadExcel($title . '信息' . date('YmdHi'), $titles, $exportData);
        return $this->buildSuccess();
    }

    public function upload(): Response {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('excel_file');
        $school_id = request()->post('school_id');
        // 上传到本地服务器
        try {
            validate(['image'=>'fileSize:20480|fileExt:xls,xlsx'])
                ->check([$file]);
            $fileExtendName = substr(strrchr($file->getOriginalName(), '.'), 1);
            $filePath = $file->getPathname();
            if (is_file($filePath)){
                $cols = [['1' => 'number'],['2' =>'type'],['3'=>'student_no'],['4'=>'name'],['5'=>'sex'],['6' => 'entrance_time'],['7'=>'graduate_time'],['8'=>'phone'],['9'=>'sim_card']];
                $data = ExcelHandle::importExcel($filePath,$cols,$fileExtendName);

                $redis = PoolRedis::instance();
                $redis->multi(\Redis::PIPELINE);
                foreach ($data as $datum) {
                    $datum['school_id'] = $school_id;
                    $redis->lPush("upload_super_sim", serialize($datum));
                }
                $redis->exec();
                Queue::push('app\task\job\UploadSyncHandlerJob@fire', [
                    'model'=> AdminStaff::class,
                    'action' => 'upload_super_sim'
                ]);
            }
            return $this->buildSuccess();
        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }
}